Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / webhooks / prodigi / [token] / route.ts

Raw 5.9 KB on f4d070c0cd6547ed6432bda0f7f1dc2cb2181b18
1import { NextResponse } from 'next/server';
2import { commerceDb } from '@/app/lib/commerce-db';
3import { sendEmail } from '@/app/lib/email';
4import { env } from '@/app/lib/env';
5import { displayOrderId } from '@/app/lib/orders';
6import { shippedHtml } from '@/app/lib/order-emails';
7import { generateMagicLink } from '@/app/lib/magic-link';
8
9export const runtime = 'nodejs';
10export const dynamic = 'force-dynamic';
11
12// CloudEvents v1.0 — Prodigi posts the full order object as `data`.
13// https://www.prodigi.com/print-api/docs/reference/#webhooks
14//
15// Prodigi fires a callback after create, after each shipment is made,
16// and after the order completes. Crucially, TRACKING arrives on the
17// "shipment made" callback — and at that point status.stage is usually
18// still "InProgress" (stage only flips to "Complete" once every shipment
19// has dispatched). So we react to the presence of a shipment, NOT to
20// stage alone, or we'd drop the tracking-bearing event.
21type ProdigiShipment = {
22 status?: string;
23 carrier?: { name?: string; service?: string };
24 tracking?: { number?: string; url?: string };
25};
26type ProdigiEvent = {
27 type?: string;
28 id?: string;
29 time?: string;
30 subject?: string;
31 data?: {
32 id?: string;
33 status?: { stage?: string; details?: { shipping?: string } };
34 shipments?: ProdigiShipment[];
35 } & Record<string, unknown>;
36};
37
38type Tracking = { number: string | null; url: string | null; carrier: string | null };
39
40// Persist tracking onto the order. Best-effort: the tracking_number /
41// tracking_url / carrier columns are an additive migration that may not
42// be applied yet — if they're missing, Postgres errors, we log and move
43// on. The shipping email (which carries tracking from the event payload)
44// and the status transition do NOT depend on this succeeding.
45async function persistTracking(
46 admin: ReturnType<typeof commerceDb>,
47 orderId: string,
48 t: Tracking,
49): Promise<void> {
50 if (!t.number && !t.url && !t.carrier) return;
51 const { error } = await admin
52 .from('orders')
53 .update({ tracking_number: t.number, tracking_url: t.url, carrier: t.carrier })
54 .eq('id', orderId);
55 if (error) console.warn('[prodigi] tracking persist skipped (run the columns migration):', error.message);
56}
57
58export async function POST(req: Request, ctx: { params: Promise<{ token: string }> }) {
59 const { token } = await ctx.params;
60 const expected = process.env.PRODIGI_WEBHOOK_TOKEN;
61 if (!expected || token !== expected) return new NextResponse('Not found', { status: 404 });
62
63 let event: ProdigiEvent;
64 try {
65 event = (await req.json()) as ProdigiEvent;
66 } catch {
67 return NextResponse.json({ error: 'invalid json' }, { status: 400 });
68 }
69
70 const prodigiOrderId = event.subject ?? event.data?.id;
71 console.log('[prodigi] webhook', { type: event.type, id: event.id, prodigiOrderId, time: event.time });
72 if (!prodigiOrderId) return NextResponse.json({ received: true, ignored: 'no order id' });
73
74 const admin = commerceDb();
75 const { data: order } = await admin
76 .from('orders')
77 .select('id, user_email, status')
78 .eq('prodigi_order_id', prodigiOrderId)
79 .single();
80 if (!order) {
81 console.warn('[prodigi] no matching order for', prodigiOrderId);
82 return NextResponse.json({ received: true, ignored: 'no matching order' });
83 }
84
85 // First shipment that carries any tracking (or is marked Shipped).
86 const shipments = event.data?.shipments ?? [];
87 const shipment = shipments.find(
88 s => s?.tracking?.number || s?.tracking?.url || s?.status === 'Shipped',
89 );
90 const tracking: Tracking = {
91 number: shipment?.tracking?.number ?? null,
92 url: shipment?.tracking?.url ?? null,
93 carrier: shipment?.carrier?.name ?? null,
94 };
95
96 const stage = event.data?.status?.stage;
97 const shippingDone = event.data?.status?.details?.shipping === 'Complete';
98 const hasShipped = !!shipment || shippingDone || stage === 'Complete';
99
100 if (stage === 'Cancelled') {
101 if (order.status !== 'cancelled') {
102 await admin.from('orders').update({ status: 'cancelled' }).eq('id', order.id);
103 }
104 return NextResponse.json({ received: true, status: 'cancelled' });
105 }
106
107 if (hasShipped) {
108 // Compare-and-swap on status ALONE (no tracking columns here, so a
109 // pending migration can't block the transition): only one callback
110 // wins the move into `shipped`, so the customer gets exactly one
111 // shipping email even though Prodigi fires the shipment + completed
112 // callbacks (and may retry). Gated to in-flight statuses so we never
113 // resurrect a cancelled order.
114 const { data: claimed } = await admin
115 .from('orders')
116 .update({ status: 'shipped' })
117 .eq('id', order.id)
118 .in('status', ['approved', 'in_production'])
119 .select('id');
120
121 // Persist tracking regardless of who won the race (best-effort).
122 await persistTracking(admin, order.id, tracking);
123
124 if (claimed && claimed.length > 0) {
125 const link =
126 (await generateMagicLink(order.user_email, `/orders/${order.id}`)) ??
127 `${env.site.url()}/orders/${order.id}`;
128 await sendEmail({
129 to: order.user_email,
130 subject: `Your portrait shipped — ${displayOrderId(order.id)}`,
131 html: shippedHtml(order.id, link, tracking),
132 text: `Your portrait shipped${tracking.carrier ? ` via ${tracking.carrier}` : ''}.${tracking.number ? ` Tracking: ${tracking.number}` : ''}${tracking.url ? ` (${tracking.url})` : ''} View your order: ${link}`,
133 }).catch(() => {});
134 return NextResponse.json({ received: true, newStatus: 'shipped', emailed: true });
135 }
136
137 // Already shipped (duplicate/late callback) — never re-send the email.
138 return NextResponse.json({ received: true, idempotent: true });
139 }
140
141 // Still in production.
142 if (stage === 'InProgress' && order.status !== 'in_production') {
143 await admin.from('orders').update({ status: 'in_production' }).eq('id', order.id);
144 }
145 return NextResponse.json({ received: true, status: order.status });
146}